package com.zhrj.exam.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhrj.exam.entity.TokenData;
import com.zhrj.exam.service.GrantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


@Service
@Slf4j
public class GrantServiceImpl implements GrantService {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public TokenData grant(String AUTHURL) throws JsonProcessingException {
        String token = (String)redisTemplate.opsForValue().get("accessToken");
        String tokenType = (String)redisTemplate.opsForValue().get("tokenType");
        if(token != null && tokenType != null){
            log.info("已获取token:{}",token);
            TokenData tokenData = new TokenData();
            tokenData.setAccessToken(token);
            tokenData.setTokenType(tokenType);
            return tokenData;
        }
        return remoteGrant(AUTHURL);
    }

    private TokenData remoteGrant(String AUTHURL) throws JsonProcessingException {
        String clientId = "saber";
        String clientSecret = "saber_secret";
        // 3. 生成 Base64 的 Authorization
        String auth = clientId + ":" + clientSecret;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        log.info("Base64 Encoded Auth: " + encodedAuth);
        // 4. 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "Basic " + encodedAuth);
        // 5. 创建请求参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "password");  // 授权类型，具体按接口文档需求
        params.add("username", "admin"); // 账号
        params.add("password", "044ba116afc769bfba4c5c568cc8912c023af73930c97271052e3b2b0198c37b67701a64c005137cc0b891c9969b3fb8576b8dc2884bf90ee1127250a755ccb43dc1d4c2374877213453e237bce3f87b4c2b5db34f14cc0ad6ef400e5650d1d209da87fd8186"); // 密码
        // 6. 封装请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        // 8. 发送 POST 请求
        ResponseEntity<String> response = restTemplate.exchange(
                AUTHURL,
                HttpMethod.POST,
                requestEntity,
                String.class
        );
        log.info("响应状态码: " + response.getStatusCodeValue());
        log.info("响应体: " + response.getBody());
        // 转换为 JSON 对象
        JsonNode jsonNode = objectMapper.readTree(response.getBody());
        JsonNode dataNode = jsonNode.path("data");
        // 获取 "accessToken" 的值
        String token = dataNode.path("accessToken").asText(null);
        String tokenType = dataNode.path("tokenType").asText(null);
        redisTemplate.opsForValue().set("accessToken",token);
        redisTemplate.opsForValue().set("tokenType",tokenType);
        // 提取 token 字段
        log.info("获取的 Token: " + token);
        JsonNode jsonNode1 = objectMapper.readTree(response.getBody());  // 解析整个 JSON 响应体
        // 获取 records 数组
        JsonNode dataNode1 = jsonNode.get("data");
        // 将 records 数组转换为 List<BladeUser>
        TokenData tokenData = objectMapper.readValue(dataNode1.toString(), TokenData.class);
        return tokenData;
    }
}
